#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 1e5 + 10, M = N * 2;
int h[N], e[M], ne[M], w[M], idx;
int n, m;
int dis[N];
bool st[N];
void add(int a, int b, int c)
{
	e[idx] = b;
	ne[idx] = h[a];
	w[idx] = c;
	h[a] = idx++;
}
void dij()
{
	memset(dis, 0x3f, sizeof(dis));
	dis[1] = 0;
	priority_queue<PII, vector<PII>, greater<PII>>heap;
	heap.push({ 0,1 });
	while (heap.size()) {
		PII t = heap.top();
		heap.pop();
		int ver = t.x;
		int distance = t.y;
		if (st[ver])continue;
		st[ver] = 1;
		for (int i = h[ver]; ~i; i = ne[i]) {
			int j = e[i];
			if (dis[j] > distance + w[i]) {
				dis[j] = distance + w[i];
				if (!st[j]) {
					heap.push({ dis[j],j });
				}
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	memset(h, -1, sizeof(h));
	while (m--) {
		int a, b, w;
		cin >> a >> b >> w;
		add(a, b, w);
		add(b, a, w);
	}
	dij();
	if (dis[n] == 0x3f3f3f3f) cout << -1 << endl;
	else cout << dis[n] << endl;
	return 0;
}